import store from '@/store';
let Socket = null
let reconnectTimer = null
const HEARTBEAT_INTERVAL = 30000 // 30秒心跳
const RECONNECT_DELAY = 5000 // 5秒重连
const userId = uni.getStorageSync('userId')
export default {
	init() {
		if (!userId) return
		const url = `wss://zhaopaper.com/ws/webSocket/${userId}`
		// 关闭旧连接
		this.close()
		Socket = uni.connectSocket({
			url: url,
			header: {
				'Content-Type': 'application/json'
			},
			method: 'GET',
			success: res => console.log('WS连接建立中...')
		})
		// 监听事件
		Socket.onOpen(() => {
			console.log('WS连接成功')
			this.startHeartbeat()
			// this.loadLocalMessages() // 加载本地历史消息
		})
		Socket.onMessage(res => {
			const msg = res.data
			if (!msg.includes('|')) {
				return msg;
			}
			const [eventType, jsonStr] = msg.split('|');
			const data = JSON.parse(jsonStr);
			store.commit('setUnreadCount', data);
			uni.$emit('updateMessage', { msg: '页面更新' })
		})
		Socket.onClose(() => {
			console.log('WS连接关闭')
			this.reconnect()
		})
		Socket.onError(err => {
			console.error('WS连接错误:', err)
			this.reconnect()
		})
	},
	handleMessage(msg) {
		// 消息分类处理
		switch (msg.type) {
			case 'like':
				this.saveMessage('likes', msg)
				break
			case 'comment':
				this.saveMessage('comments', msg)
				break
			case 'reply':
				this.saveMessage('replies', msg)
				break
			default:
				console.warn('未知消息类型:', msg)
		}
	},
	saveMessage(type, msg) {
		// 获取本地存储
		const storageKey = `msg_${type}`
		let messages = uni.getStorageSync(storageKey) || []
		// 添加新消息并存储
		messages.unshift({
			id: Date.now(),
			content: msg.content,
			timestamp: new Date().toISOString(),
			read: false
		})
		uni.setStorageSync(storageKey, messages.slice(0, 100)) // 保留最新100条
		// 触发全局事件
		uni.$emit('new-message', {
			type,
			data: messages
		})
	},
	startHeartbeat() {
		clearInterval(this.heartbeatTimer)
		this.heartbeatTimer = setInterval(() => {
			this.send({
				type: 'heartbeat'
			})
		}, HEARTBEAT_INTERVAL)
	},
	reconnect() {
		clearTimeout(reconnectTimer)
		reconnectTimer = setTimeout(() => {
			const userId = uni.getStorageSync('userId')
			userId && this.init()
		}, RECONNECT_DELAY)
	},
	send(data) {
		if (Socket && Socket.readyState === 1) {
			Socket.send({
				data: JSON.stringify(data),
				success: () => console.debug('消息发送成功')
			})
		}
	},
	close() {
		clearInterval(this.heartbeatTimer)
		Socket && Socket.close()
	}
}